package com.dgy.examTools.service.impl;

import com.dgy.examTools.domain.Student;
import com.dgy.examTools.mapper.StudentMapper;
import com.dgy.examTools.service.IStudentService;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.*;
import com.itextpdf.layout.properties.HorizontalAlignment;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.UnitValue;
import com.ruoyi.common.utils.pdf.PdfUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.List;

@Service
public class StudentServiceImpl implements IStudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public List<String> getAllKaochang() {
        return studentMapper.getkaochangList();
    }

    @Override
    public List<Student> getStudentByKaoChang(String kaoChang) {
        return studentMapper.selectStudentListByKaochang(kaoChang);
    }

    @Override
    public void generateExamSignPdfList() {
        // 获取所有考场名字
        List<String> kaochangList = this.getAllKaochang();
        if(kaochangList.size() <= 0){
            System.out.println("没获取到考场信息");
        }
        // 循环考场名获取考场学生名单
        for (String kaochang : kaochangList) {
            List<Student> studentList = this.getStudentByKaoChang(kaochang);
            if(kaochangList.size() <= 0){
                System.out.println(kaochang+"没有查询到学生信息");
            }
            // 生成该考场pdf文件
            this.generatePdf(studentList,studentList.get(0).getKaoshiType(),kaochang);
        }
    }

    /**
     * 生成一个考场的pdf
     * @param studentList 学生列表
     * @param examType 考试类型。1:单招 2:综合。3:退役军人
     * @param kaochang 考场号
     *
     */
    private void generatePdf(List<Student> studentList,Integer examType , String kaochang) {
        String dest = kaochang+".pdf";
        try {
            // 创建 PDF 文档
            PdfWriter writer = new PdfWriter(new File(dest));
            PdfDocument pdf = new PdfDocument(writer);
            Document document = new Document(pdf);
            // 指定支持中文的系统字体，如宋体
            String titleFontPath = "/Library/Fonts/楷体_GB2312.TTF";
            PdfFont titleFont = PdfFontFactory.createFont(titleFontPath, "Identity-H");
            // 添加标题
            String title = "德州工程职业技术学院";
            Paragraph titleParagraph = new Paragraph(title);
            titleParagraph.setFont(titleFont);
            titleParagraph.setFont(titleFont);
            titleParagraph.setFontSize(18); // 设置标题字体大小
            titleParagraph.setFixedLeading(15);
            titleParagraph.setTextAlignment(TextAlignment.CENTER); // 标题居中显示
            document.add(titleParagraph);
            // 添加标题
            String title2 = "2025年高职（专科）单独考试招生";
            if(examType == 2){
                title2 = "2025年高职（专科）综合评价招生考试";
            }
            Paragraph title2Paragraph = new Paragraph(title2);
            title2Paragraph.setFont(titleFont);
            title2Paragraph.setFontSize(18); // 设置标题字体大小
            title2Paragraph.setFixedLeading(15);
            title2Paragraph.setTextAlignment(TextAlignment.CENTER); // 标题居中显示
            document.add(title2Paragraph);
            // 添加标题
            String title3 = "考生签到表";
            Paragraph title3Paragraph = new Paragraph(title3);
            title3Paragraph.setFont(titleFont);
            title3Paragraph.setFontSize(18); // 设置标题字体大小
            title3Paragraph.setFixedLeading(15);
            title3Paragraph.setTextAlignment(TextAlignment.CENTER); // 标题居中显示
            document.add(title3Paragraph);

            document.add(new Paragraph(" "));
            document.add(new Paragraph(" "));
            document.add(new Paragraph(" "));

            // 正文字体仿宋
            String contentFontPath = "/Library/Fonts/SIMHEI.TTF";
            PdfFont font = PdfFontFactory.createFont(contentFontPath, "Identity-H");
            // 考试时间
            Div subtitleDiv = new Div();
            subtitleDiv.setWidth(UnitValue.createPercentValue(100));
            subtitleDiv.setHorizontalAlignment(HorizontalAlignment.CENTER);
            // 创建一个表格来布局副标题，一行两列
            Table subtitleTable = new Table(2);
            subtitleTable.setWidth(UnitValue.createPercentValue(100));
            subtitleTable.setBorder(null);

            // 左侧副标题
            String leftTitle = "考场："+kaochang;
            if(examType == 2){
                leftTitle = "面试场："+kaochang;
            }
            Paragraph leftSubtitlePara = new Paragraph(leftTitle);
            leftSubtitlePara.setFont(font);
            Cell leftCell = new Cell().add(leftSubtitlePara);
            leftCell.setBorder(null);
            leftCell.setTextAlignment(TextAlignment.LEFT);
            subtitleTable.addCell(leftCell);

            // 右侧副标题
            Paragraph rightSubtitlePara = new Paragraph("考试时间：2025年3月2日 9:30～11:30");
            rightSubtitlePara.setFont(font);
            Cell rightCell = new Cell().add(rightSubtitlePara);
            rightCell.setBorder(null);
            rightCell.setTextAlignment(TextAlignment.RIGHT);
            subtitleTable.addCell(rightCell);

            subtitleDiv.add(subtitleTable);
            document.add(subtitleDiv);

            // 添加空段落，用于在标题和表格之间留出间距
            document.add(new Paragraph(" "));

            // 假设每行显示 4 组学生信息
            int studentsPerRow = 5;
            // 创建表格，列数为每组信息的列数（照片和姓名）乘以每行显示的组数
            Table table = new Table(studentsPerRow);
            // 设置列间距
            table.setHorizontalAlignment(HorizontalAlignment.LEFT);
            table.setMarginBottom(10);
            table.setPadding(5);
            // 遍历学生信息，添加到表格中
            for (Student student : studentList) {
                Cell studentCell = new Cell();
                studentCell.setPadding(2);
                try {
                    // 添加照片
                    String a = "/Users/ccc/Desktop/img/"+student.getExamNumber()+".jpg";
                    ImageData imageData = ImageDataFactory.create(a);
                    Image image = new Image(imageData);
                    image.setWidth(90); // 设置照片宽度
                    image.setHorizontalAlignment(HorizontalAlignment.CENTER);
                    studentCell.add(image);
                } catch (IOException e) {
                    System.err.println("无法加载学生：" +student.getName() + " 的照片: " + e.getMessage());
                    Paragraph errorParagraph = new Paragraph("照片加载失败");
                    errorParagraph.setTextAlignment(TextAlignment.CENTER);
                    studentCell.add(errorParagraph);
                }

                // 添加姓名
                Paragraph nameParagraph = new Paragraph("姓名："+student.getName());
                nameParagraph.setTextAlignment(TextAlignment.LEFT);
                nameParagraph.setFont(font);
                nameParagraph.setFontSize(9); // 设置标题字体大小
                studentCell.add(nameParagraph);

                // 准考证号
                Paragraph codeParagraph = new Paragraph("考号："+student.getExamNumber());
                codeParagraph.setTextAlignment(TextAlignment.LEFT);
                codeParagraph.setFont(font);
                codeParagraph.setFontSize(9); // 设置标题字体大小
                studentCell.add(codeParagraph);

                // 座位号
                Paragraph seatParagraph = new Paragraph("座号："+student.getZuoweihao());
                seatParagraph.setTextAlignment(TextAlignment.LEFT);
                seatParagraph.setFont(font);
                seatParagraph.setFontSize(9); // 设置标题字体大小
                studentCell.add(seatParagraph);

                // 考生签字
                Paragraph remarkParagraph = new Paragraph("签名：         ");
                remarkParagraph.setTextAlignment(TextAlignment.LEFT);
                remarkParagraph.setFont(font);
                remarkParagraph.setFontSize(9); // 设置标题字体大小
                studentCell.add(remarkParagraph);
                table.addCell(studentCell);
            }
            // 将表格添加到文档中
            document.add(table);

            // 添加空段落，用于在标题和表格之间留出间距
            document.add(new Paragraph(" "));
            document.add(new Paragraph(" "));
            document.add(new Paragraph(" "));
            // 文件底部信息
            String end1 = "考生人数：                 实到人数：                  缺考人数：                   ";
            Paragraph endParagraph1 = new Paragraph(end1);
            endParagraph1.setFont(font);
            endParagraph1.setFontSize(12); // 设置标题字体大小
            endParagraph1.setTextAlignment(TextAlignment.LEFT); // 标题居中显示
            document.add(endParagraph1);
            document.add(new Paragraph(" "));
            document.add(new Paragraph(" "));
            document.add(new Paragraph(" "));
            document.add(new Paragraph(" "));
            // 文件底部信息
            String end = "监考签字：                                    ";
            Paragraph endParagraph = new Paragraph(end);
            endParagraph.setFont(font);
            endParagraph.setFontSize(12); // 设置标题字体大小
            endParagraph.setTextAlignment(TextAlignment.RIGHT); // 标题居中显示
            document.add(endParagraph);

            // 为每一页添加页眉和页脚
            int numberOfPages = pdf.getNumberOfPages();
            for (int pageNumber = 1; pageNumber <= numberOfPages; pageNumber++) {
                PdfPage page = pdf.getPage(pageNumber);
//                addHeader(page, font);
                PdfUtil.addFooter(page, font, "页脚");
            }
            // 关闭文档
            document.close();
            System.out.println("PDF 文件生成成功：" + dest);
        } catch (IOException e) {
            System.out.println("PDF 文件生成成功：" + dest);
            e.printStackTrace();
        }
    }

}
